package com.antipov.odp;

import com.antipov.odp.pojo.A;
import com.antipov.odp.pojo.B;
import com.antipov.odp.pojo.C;
import com.antipov.odp.pojo.I;

import java.io.FileWriter;
import java.io.IOException;
import java.io.StreamTokenizer;
import java.io.Writer;
/**
 * Created with IntelliJ IDEA.
 * User: Andrew Antipov
 * Date: 18.02.14
 * Time: 22:25
 */
public class IOHelper {

	public static void saveData(I[] data, String fileName) throws IOException{
		Writer writer = new FileWriter(fileName);
		writer.append(Integer.toString(data.length) + '\n');
		for(I element: data) {
			saveElement(element, writer);
		}
		writer.flush();
		writer.close();
	}

	private static void saveElement(I i, Writer writer) throws IOException {
		writer.append(i.toString());
		writer.append('\n');
	}

	public static I readNext(StreamTokenizer tok) throws IOException {
		int type = nextInt(tok);
		int arrayLength = nextInt(tok);
		int[] array = new int[arrayLength];
		for (int i = 0; i < arrayLength; i++) {
			array[i] = nextInt(tok);
		}
		int x = nextInt(tok);
		switch (type) {
			case A.ID:
				return new A(array, x);
			case B.ID:
				double d = nextDouble(tok);
				return new B(array, x, d);
			case C.ID:
				String temp = nextString(tok);
				if (temp.length() != 1) {
					throw new IOException();
				}
				char c = temp.charAt(0);
				return new C(array, x, c);
		}
		throw new IOException("Unknown type");
	}


	public static int nextInt(StreamTokenizer tok) throws IOException {
		tok.nextToken();
		if (tok.ttype != StreamTokenizer.TT_NUMBER) {
			throw new IOException("Bad data");
		}
		return (int) tok.nval;
	}

	private static double nextDouble(StreamTokenizer tok) throws IOException {
		tok.nextToken();
		if (tok.ttype != StreamTokenizer.TT_NUMBER) {
			throw new IOException("Bad data");
		}
		return tok.nval;
	}

	public static String nextString(StreamTokenizer tok) throws IOException {
		tok.nextToken();
		if (tok.ttype != StreamTokenizer.TT_WORD) {
			throw new IOException("Bad data");
		}
		return tok.sval;
	}
}
